import store from "../store";
import './Define.js'
import {MessageType} from "./Define.js";

export const connect = () => {
    store.dispatch({type: 'tipsPush', data: '正在建立 WebSocket 连接...'})

    let ws = new WebSocket('ws://localhost:8090/ws?name=' + store.getState().userName);

    ws.onopen = () => {
        store.dispatch({type: 'tipsPush', data: 'WebSocket 连接已建立...'})
        store.dispatch({type: 'socketConnect', data: ws})
    }

    ws.onmessage = (e) => {
        let data = JSON.parse(e.data)

        switch (data.type){
            case MessageType.join:
            case MessageType.leave:
                store.dispatch({type: 'tipsPush', data: data.message})

                if (data.data?.user_list) {
                    store.dispatch({type: 'setUserList', data: data.data.user_list})
                }
                break
            case MessageType.user:
                store.dispatch({type: 'setUserId', data: data.message_to})
                break
            case MessageType.send:
                store.dispatch({type: 'pushMessage', data: data})
                break
        }
    }

    ws.onclose = () => {
        if (store.getState().webSocket) {
            store.dispatch({type: 'tipsPush', data: 'WebSocket 连接已断开...'})
        }
    }

    ws.onerror = (e) => {
        store.dispatch({type: 'tipsPush', data: 'WebSocket 连接错误...'})
    }
}

export const sendMessage = (message, id = '') => {
    let ws = store.getState().webSocket

    ws.send(JSON.stringify({
        message_from: store.getState().userId,
        message_to: id,
        message: message
    }))
}